/**
 * 请求头的各种设置
 */
let apiHttp = require('../config').baseUrl

function fun(url, method, data, header) {
  let a="/null/"
  let newurl=url.replace(/(\/\/)/g, a)
  data = data || {};
  header = header || {};
  let sessionId = wx.getStorageSync("UserSessionId");
  if (sessionId) {
    if (!header || !header["SESSIONID"]) {
      header["SESSIONID"] = sessionId;
    }
  }
  let promise = new Promise(function (resolve, reject) {
    
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
      mask:true,
    })
    wx.request({
      url: apiHttp + newurl,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        if (res.statusCode == 200) {
          resolve(res);
        } 
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '网络请求超时,请重新连接',
          success(res) {}
        })
        reject(res)
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  });
  return promise;
}

function upload(url, name, filePath) {
  let header = {};
  let sessionId = wx.getStorageSync("UserSessionId"); //从缓存中拿该信息
  if (sessionId) {
    if (!header || !header["SESSIONID"]) {
      header["SESSIONID"] = sessionId; //添加到请求头中
    }
  }
  wx.showNavigationBarLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.uploadFile({
      url: apiHttp + url,
      filePath: filePath,
      name: name,
      header: header,
      success: function (res) {
        resolve(res);
      },
      fail: reject,
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}
// 发起各种请求的地方
module.exports = {
  apiHttp: apiHttp,
  "get": function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  "post": function (url, data, header) {
    return fun(url, "POST", data, header);
  },
  upload: function (url, name, filePath) {
    return upload(url, name, filePath);
  }
};
// Request.post('', //调用方法
//   {
//   }, {
//     'content-type': 'application/json', // 默认值
//   },
// ).then(res => { //成功回调
// }).catch(err => {}) //异常回调


// Request.upload('', //调用方法
//   {
//     name
//   }, {
//     filePath
//   }, {
//     'content-type': 'multipart/form-data',
//   },
// ).then(res => { //成功回调
// }).catch(err => {}) //异常回调


// let Request = require(""); //导入模块